<template>
	<div>
		<div class="container">
			<div class="handle-box">
				<el-input v-model="query.activityName" placeholder="活动名称" class="handle-input mr10"></el-input>
				<el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
				<el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
			</div>
			<el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
				<el-table-column prop="activityId" label="活动ID" align="center"></el-table-column>
				<el-table-column prop="activityName" label="活动名称" align="center"></el-table-column>
				<el-table-column prop="activityDesc" label="活动描述" align="center"></el-table-column>
				<el-table-column prop="strategyId" label="策略" align="center"></el-table-column>
				<el-table-column prop="stockCount" label="总库存" align="center"></el-table-column>
				<el-table-column prop="stockSurplusCount" label="剩余库存" align="center"></el-table-column>
				<el-table-column prop="takeCount" label="领取次数" align="center"></el-table-column>
				<el-table-column prop="beginDateTime" label="活动开始时间" align="center"></el-table-column>
				<el-table-column prop="endDateTime" label="活动结束时间" align="center"></el-table-column>
				<el-table-column prop="state" label="活动状态" align="center">
					<template #default="scope">
						<span v-if="scope.row.state === 1">编辑</span>
						<span v-else-if="scope.row.state === 5">运行中</span>
						<span v-else>未运行状态（{{ scope.row.state }}）</span>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
				<el-table-column label="操作" width="220" align="center">
					<template #default="scope">
						<el-button text :icon="Edit" @click="handleEdit(scope.$index, scope.row)" v-permiss="15">
							编辑
						</el-button>
						<el-button text :icon="Delete" class="red" @click="handleDelete(scope.$index, scope.row)" v-permiss="16">
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination
					background
					layout="total, prev, pager, next"
					:current-page="query.pageNum"
					:page-size="query.pageSize"
					:total="pageTotal"
					@current-change="handlePageChange"
				></el-pagination>
			</div>
		</div>
<!-- 新增框弹出 -->
		<el-dialog title="新增" v-model="addVisible" width="70%">
			<el-form label-width="70px">
			
				<el-form-item label="活动名称">
					<el-input v-model="addForm.activityName"></el-input>
				</el-form-item >
				<el-form-item label="活动描述">
					<el-input v-model="addForm.activityDesc"></el-input>
				</el-form-item >
				
				<el-form-item label="选择策略" prop="awardType">
				<el-select v-model="addForm.strategyId" placeholder="请选择策略">
					<el-option v-for="type in strategyTypesData" :key="type.strategyId" :label="type.strategyDesc" :value="type.strategyId"></el-option>
				</el-select>
				</el-form-item>
				<el-form-item label="活动库存">
					<el-input v-model="addForm.stockCount"></el-input>
				</el-form-item>
				<el-form-item label="领取次数">
					<el-input v-model="addForm.takeCount" placeholder="每人领取次数" ></el-input>
				</el-form-item>
				<el-form-item label="执行时间">
					<div class="block">
						<el-date-picker
						v-model="value2"
						type="datetimerange"
						:shortcuts="shortcuts"
						range-separator="-"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						 @change="handleChange"  style="display: inline-block;"
						/>
 				 </div>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="addVisible = false">取 消</el-button>
					<el-button type="primary" @click="saveAdd">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		
		<!-- 编辑弹出框 -->
		<el-dialog title="编辑" v-model="editVisible" width="30%">
			<el-form label-width="70px" :model = "editForm">
				<el-form-item label="活动名称" prop = "activityName">
					<el-input v-model="editForm.activityName"></el-input>
				</el-form-item>
				<el-form-item label="活动描述" prop = "activityDesc">
					<el-input v-model="editForm.activityDesc"></el-input>
				</el-form-item>
						
				<el-form-item label="选择策略" prop = "awardType">
				<el-select v-model="editForm.strategyId" placeholder="请选择策略">
					<el-option v-for="type in strategyTypesData" :key="type.strategyId" :label="type.strategyDesc" :value="type.strategyId"></el-option>
				</el-select>
				</el-form-item>
				<el-form-item label="活动库存" prop = "stockCount">
					<el-input v-model="editForm.stockCount"></el-input>
				</el-form-item>
				<el-form-item label="领取次数" prop = "takeCount">
					<el-input v-model="editForm.takeCount" placeholder="每人领取次数" ></el-input>
				</el-form-item>
				<el-form-item label="执行时间">
					<div class="block">
						<el-date-picker
						v-model="value2"
						type="datetimerange"
						:shortcuts="shortcuts"
						range-separator="-"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						 @change="handleChange"  style="display: inline-block;"
						/>
 				 </div>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="editVisible = false">取 消</el-button>
					<el-button type="primary" @click="saveEdit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit, Search, Plus } from '@element-plus/icons-vue';
import { addActivity, queryActivityInfoLimitPage,queryStrategyConfig, deleteActivity, editActivity } from '../api/lottery';

interface TableItem {
	activityId: number,
	activityName: string;
	activityDesc: string;
	strategyId: string;
	stockCount: number;
	stockSurplusCount: number;
	takeCount: number;
	state: number;
	creator: number;
	beginDateTime: string;
	endDateTime: string;
	createTime: string;
	updateTime: string;
}

const query = reactive({
	activityName:null,
	pageNum: 0,
	pageSize: 10
});
const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);
// 获取表格数据
const getData = () => {
	queryActivityInfoLimitPage(query).then(res => {
		console.log(res)
		tableData.value = res.data.activityVOList;
		pageTotal.value = res.data.pageTotal || 0;
	});
};
getData();
// 查询操作
const handleSearch = () => {
	query.pageNum = 1;
	getData();
};
// 分页导航
const handlePageChange = (val: number) => {
	query.pageNum = val;
	getData();
};
// 处理下拉框展示策略数据 -start 
interface StrategyTypes {
	strategyId:number,
	strategyDesc:string
}
const strategyTypesData = ref<StrategyTypes[]>([]);
const getStrategydData = () => {
	queryStrategyConfig(null).then(res => {
		console.log(res)
		strategyTypesData.value=res.data
	});
};
getStrategydData();
// 处理下拉框展示策略数据 -end 
// 新增弹出框
const addVisible = ref(false);
let addForm = reactive({
	activityName: '',
	activityDesc: '',
	stockCount: '',
	stockSurplusCount: '',
	takeCount: '',
	strategyId: '',
	beginDateTime: null,
	endDateTime: null,
	

});
const handleAdd = () => {
	addVisible.value = true;
};
const saveAdd = () => {
	addVisible.value = false;
	console.log("新增数据:" , JSON.stringify(addForm))
	addActivity(addForm).then(res => {
		if(res.data.code === "0000"){
				ElMessage.success(res.data.info);
				getData();
			}else{
				ElMessage.error(res.data.info);
			}
	})

	

};
// 日期处理
const value2 = ref([null, null]);
const startDate = ref(null);
const endDate = ref(null);
const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

function handleChange(value:any) {
  const [startValue, endValue] = value;

  // 将日期转换为ISO 8601格式的字符串
	startDate.value = startValue.toISOString();
	endDate.value = endValue.toISOString();
	console.log("开始时间：",startDate.value)
	console.log("结束时间：",endDate.value)
	addForm.beginDateTime = startDate.value
	addForm.endDateTime = endDate.value
	editForm.value.beginDateTime = startDate.value;
	editForm.value.endDateTime = endDate.value;

  };


let deleteParam = reactive({
	activityId: null
});

// 删除操作
const handleDelete = (index: number, row: any) => {
	// 二次确认删除
	// console.log("当前行数据:", deleteParam);
	ElMessageBox.confirm('确定要删除吗？', '提示', {
		type: 'warning'
	})
		.then(() => {
			deleteActivity(row.activityId).then((resp) => {
				if (resp.data.code == "0000") {
					ElMessage.success('删除成功');
					tableData.value.splice(index, 1);
				} else {
					ElMessage.warning(resp.data.info);
				}

			})
		})
		.catch(() => {});
};

// 表格编辑时弹窗和保存
const editVisible = ref(false);
let editForm = 
	ref({
	activityId: null,
	activityName: '',
	activityDesc: '',
	stockCount: '',
	stockSurplusCount: '',
	takeCount: '',
	strategyId: '',
	beginDateTime: null,
	endDateTime: null,
}
);
let idx: number = -1;

// 填充编辑表格内容
const handleEdit = (index: number, row: any) => {
	idx = index;
	console.log("目标row数据：", row);
	editForm.value = row;
	console.log("编辑栏中数据：", editForm);
	editVisible.value = true;
};
// 提交编辑
const saveEdit = () => {
	editVisible.value = false;
	console.log("修改数据:" , JSON.stringify(editForm.value))
	// 调用后端更新
	editActivity(editForm.value).then(res => {
		if(res.data.code === "0000"){
				ElMessage.success(res.data.info);
				getData();
			}else{
				ElMessage.error(res.data.info);
			}
	})

};
</script>

<style scoped>
.handle-box {
	margin-bottom: 20px;
}

.handle-select {
	width: 120px;
}

.handle-input {
	width: 300px;
}
.table {
	width: 100%;
	font-size: 14px;
}
.red {
	color: #F56C6C;
}
.mr10 {
	margin-right: 10px;
}
.table-td-thumb {
	display: block;
	margin: auto;
	width: 40px;
	height: 40px;
}
.block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.block .date-picker-container {
  display: flex;
  align-items: center;
}
</style>
